package com.example.demo.controller;
import com.example.demo.model.Student;
import com.example.demo.repository.StudentRepository;
import com.example.demo.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;

import org.springframework.web.bind.annotation.RequestMapping;

import java.util.*;


@Controller
public class StudentController {
    @Autowired
    private StudentRepository studentRepository;

    @Autowired
    private StudentService studentService;
    private static Map<String,Student> students = new HashMap<>();
    static{
        Student s1 = new Student("1","tony");
        students.put(s1.getId(),s1);
        Student s2 = new Student("2","jerry");
        students.put(s2.getId(),s2);
    }
    @RequestMapping("search")
    public String search(ModelMap map,Student student){
        if("".equals(student.getName())){
            student.setName(null);
        }
       // List<Student> students = studentRepository.findByNameOrAge(student.getName(),student.getAge());
        List<Student> students = studentRepository.findAll(Example.of(student));
        map.put("studentList",students);
        return "list";
    }
   @RequestMapping("list")
    public String list(ModelMap map,Student student){
       if("".equals(student.getName())){
           student.setName(null);
       }
        map.put("studentList",studentService.findAll(student));
        return "list";
   }
    @RequestMapping("/delete/{id}")
    public String delete(@PathVariable String id){
        studentService.deleteById(id);
        return "redirect:/list";
    }


    @RequestMapping("create")
    public String create(){
        return "create";
    }

    @RequestMapping("save")
    public String save(Student s){
        if(s.getId()==null)
        {
            s.setId(UUID.randomUUID().toString());
        }
        //System.out.println(s.getName());

        studentService.save(s);
        return "redirect:/list";
    }

    @RequestMapping("update/{id}")
    public String update(@PathVariable String id,ModelMap map){
        Student s = studentService.getReferenceById(id);
        map.put("student",s);
        return "update";
    }
}
